package com.wlyuan.index.remote.consumer;

import com.wlyuan.index.api.IWaybillIndexService;
import com.wlyuan.index.remote.message.WaybillMessage;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author yuanjie
 */
@Slf4j
@Component
public class WaybillMessageConsumer extends AbstractMessageConsumer<WaybillMessage> {
    @Resource
    private IWaybillIndexService waybillIndexService;

    @RabbitListener(bindings = {@QueueBinding(value = @Queue(
            value = Queues.WAYBILL_REINDEX),
            exchange = @Exchange(value = Exchanges.TRANSPORT),
            key = {"WaybillRefused", "WaybillDispatched"})
    }, concurrency = "2")
    public void consumeSome(String string) {
        logger.debug("~收到运单消息: {}", string);
        try {
            this.handle(string, WaybillMessage.class, message -> {
                var waybill = message.getWaybill();
                waybillIndexService.reindex(waybill.getWaybillId());
            });
        } catch (Exception e) {
            logger.error("~处理运单息失败：{}", string, e);
        }
    }

    @RabbitListener(bindings = {@QueueBinding(value = @Queue(
            value = Queues.WAYBILL),
            exchange = @Exchange(value = Exchanges.TRANSPORT),
            key = {
                    "WaybillCreated", "WaybillUpdated", "WaybillAccepted",
                    "WaybillSigned", "WaybillReceipted", "WaybillReceiptLosed",
                    "WaybillDeviceBound", "WaybillConfirmed", "WaybillCloseApplied",
                    "WaybillClosed", "WaybillCloseRefused", "WaybillDivided",
                    "WaybillDivideCanceled", "WaybillUncombined",
                    "WaybillReceiptPicSynced", "WaybillBillDayClosed",
                    "WaybillBillDayCloseCanceled"
            })}, concurrency = "4")
    public void consume(String string) {
        if (logger.isDebugEnabled()) {
            logger.debug("收到运单消息: {}", string);
        }
        try {
            this.handle(string, WaybillMessage.class, message -> {
                var waybill = message.getWaybill();
                waybillIndexService.index(waybill);
            });
        } catch (Exception e) {
            logger.error("处理运单消息失败：{}", string, e);
        }
    }
}
